package org.snusmumr.android.media.data.adapter;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.snusmumr.android.media.Constants;
import org.snusmumr.android.media.Constants.ItemCheckState;
import org.snusmumr.android.media.R;
import org.snusmumr.android.media.bean.LabelModel;
import org.snusmumr.android.media.data.MediaColumns;
import org.snusmumr.android.media.util.Bits;
import org.snusmumr.android.media.util.Utils;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;

public class MediaListAdapter extends ResourceCursorAdapter {
	protected static final String TAG = MediaListAdapter.class.getSimpleName();
	private Map<Long, LabelModel> labelsMap;
	private DateFormat dateFormat; 
	private OnCheckedListener checkedListener;
	private int authorIndex;
	private int itemNameIndex;
	private int lentToFriendNameIndex;
	private int lendDateIndex;
	private int labelsMaskIndex;
	private ItemCheckState checkState = ItemCheckState.All;
	
	public interface OnCheckedListener {
		public void onChecked(boolean isChecked, int position);
	}

	public MediaListAdapter(Context context, Cursor c, SQLiteDatabase mDatabase, OnCheckedListener checkedListener) {
		super(context, R.layout.media_list_content, c);
		this.dateFormat = android.text.format.DateFormat.getMediumDateFormat(context.getApplicationContext());
		this.checkedListener = checkedListener;
		
		this.authorIndex = c.getColumnIndex(MediaColumns.AUTHOR_NAME);
		this.itemNameIndex = c.getColumnIndex(MediaColumns.ITEM_NAME);
		this.lentToFriendNameIndex = c.getColumnIndex(MediaColumns.LENT_TO_NAME);
		this.lendDateIndex = c.getColumnIndex(MediaColumns.LEND_DATE);
		this.labelsMaskIndex = c.getColumnIndex(MediaColumns.LABELS_MASK);
		
		Cursor cursor = mDatabase.query(Constants.DB_TABLE_LABEL, 
				new String[]{MediaColumns._ID,
								MediaColumns.NAME,
								MediaColumns.COLOR}, 
				null, null, null, null, null);
		labelsMap = new TreeMap<Long, LabelModel>();
		if(cursor != null) {
			while (cursor.moveToNext()) {
				LabelModel lm = new LabelModel(cursor.getLong(0), cursor.getString(1), cursor.getInt(2));
				labelsMap.put(lm.getId(), lm);
			}
			cursor.close();
		}
	}
	
	@Override
	public long getItemId(int position) {
		long id = super.getItemId(position);
		Log.d(TAG, "position: " + position + "; itemID=" + id);
		return id;
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		
		String author = cursor.getString(authorIndex);
		String itemName = cursor.getString(itemNameIndex);
		String labelsMask = cursor.getString(labelsMaskIndex);
		String lentDateStr = cursor.getString(lendDateIndex);
		String lentTo = cursor.getString(lentToFriendNameIndex);
		
		CheckBox checkBox = (CheckBox) view.findViewById(R.id.check_media_list_item);
		TextView labelsView = (TextView) view.findViewById(R.id.tv_media_list_labels);
		TextView authorView = (TextView) view.findViewById(R.id.tv_media_list_author);
		TextView itemNameView = (TextView) view.findViewById(R.id.tv_media_list_name);
		TextView lentToView = (TextView) view.findViewById(R.id.tv_media_list_lent_to);
		
		authorView.setText(author);
		itemNameView.setText(">> " + itemName);
		String lentToFull = "";
		try {
			Date lentDate = Utils.getDateFromDB(lentDateStr);
			if(lentDate != null)
				lentToFull = dateFormat.format(lentDate) + ": ";
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if(lentTo != null)
			lentToFull += lentTo;
		lentToView.setText(lentToFull);
		
		List<Integer> idArray = Bits.getBits(labelsMask);
		StringBuilder buf = new StringBuilder();
		if(idArray != null && idArray.size() > 0) {
			int size = idArray.size();
			for(int i=0; i<size; i++) {
				Integer id = idArray.get(i);
				LabelModel label = labelsMap.get(Long.valueOf(id));
				if(label != null) {
					if(buf.length() > 0)
						buf.append("\n");
					buf.append(label.getValue());
				}
			}
		}
		labelsView.setText(buf);
		
//		final boolean isLent = lentTo != null;
//		int position = cursor.getPosition();
//		checkBox.setOnCheckedChangeListener(new CheckListener(position, selected) {
//			@Override
//			public void onChecked(boolean isChecked, int position,
//					int checkedCount) {
//				checkedListener.onChecked(isChecked, position, checkedCount);
//				if(MediaListAdapter.this.checkState == ItemCheckState.All) {
//					// first check accurred
//					if(isLent)
//						MediaListAdapter.this.checkState = ItemCheckState.Lent;
//					else
//						MediaListAdapter.this.checkState = ItemCheckState.Free;
//					refreshCheckbuttonState();
//				} else if(selected.size() == 0) {
//					MediaListAdapter.this.checkState = ItemCheckState.All;
//					refreshCheckbuttonState();
//				}
//			}
//			
//		});
//		boolean selectedValue = selected.contains(position);
//		checkBox.setChecked(selectedValue);
//		if(checkState == ItemCheckState.Lent && !isLent)
//			checkBox.setEnabled(false);
//		else if(checkState == ItemCheckState.Free && isLent)
//			checkBox.setEnabled(false);
//		else checkBox.setEnabled(true);
		final int position = cursor.getPosition();
		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				checkedListener.onChecked(isChecked, position);
			}
		});
		
	}
	
	private void refreshCheckbuttonState() {

		
	}
}
